import { Progress, Message } from '@arco-design/web-react';
import { Button, Upload } from 'antd';
import React, { useCallback, useEffect, useState } from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { uploadImg } from '../../../api/upload';

interface Props {
  handleSubmitImage: (url: string) => void;
}

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}


function beforeUpload(file) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    Message.error('仅支持JPG/PNG文件');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    Message.error('图片必须小于2MB!');
  }
  return isJpgOrPng && isLt2M;
}


export const ImageUpload = (props: Props) => {
  const { handleSubmitImage } = props;
  const [imageUrl, setImageUrl] = useState();

  const handleChange = useCallback(async info => {
    if (info.status === 'init') {
      return;
    }
    const result = await uploadImg({
      file: info,
    });

    console.log(result);

    if (info.file.status === 'done') {
      // 获取服务器返回值
      const { response } = info.file;
      if (response.data) {

      }

      getBase64(info.file.originFile, imageUrl =>
        setImageUrl(imageUrl)
      );
    }
  }, []);

  // useEffect(() => {

  //   initData();
  // }, [file]);

  return (<Upload
    showUploadList={false}
    action="//localhost:7001/upload"
    beforeUpload={beforeUpload}
    onChange={(info) => {
      if (info.file.status === 'uploading') {
        return;
      }
      if (info.file.status === 'done') {
        // 获取服务器返回值
        const { response } = info.file;
        if (response.data) {
          handleSubmitImage(response.data.file)
        }
      }
    }}

  >
    <Button icon={<UploadOutlined />}></Button>
  </Upload >)
  // (
  //   <form method="POST" action="//localhost:7001/upload">

  //     file: <input name="file" type="file" />
  //     <button type="submit">Upload</button>
  //   </form>
  // )



}